import type {ConfigEnv, UserConfig} from "vite";
import {defineConfig, loadEnv} from "vite";
import vue from "@vitejs/plugin-vue";
import Unocss from "unocss/vite";
import {presetAttributify, presetIcons, presetUno, transformerDirectives, transformerVariantGroup,} from 'unocss'
import process from "node:process";
import path from "node:path";
import moment from "moment";

// https://vitejs.dev/config/
export default defineConfig((env: ConfigEnv): UserConfig => {
    const viteEnv = loadEnv(env.mode, process.cwd());
    //打包输出路径
    let outDir: any;
	const version = moment().format('YYMMDDHH');

    switch (env.mode) {
        case 'development':
            outDir = path.resolve(process.cwd(), `./${viteEnv.VITE_APP_OUT_DIR}_${version}`);
            break
        case 'test':
        case 'production':
            // 将“应用根路径”作为打包输出目录名称（不建议应用根路径存在多级）
            // nginx部署时配置
            //location /katze_web { // 输出目录名称
            // 		root    E:\idea-workspace\katze-fontend-v2;  //输出目录的父路径
            // 		try_files $uri $uri/ /katze_web/index.html;  //index.html 前要加上输出目录名称
            //}
            outDir = path.resolve(process.cwd(), `${viteEnv.VITE_APP_OUT_DIR}_${version}`);
            break
    }

    return {
        base: "./",
        resolve: {
            // 配置别名
            alias: {
                "@": path.resolve(__dirname, "src"),
                "vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js",
            },
            extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
        },
        plugins: [
            vue(), // https://github.com/antfu/unocss
            // see unocss.config.ts for config
            Unocss({
                presets: [
                    presetUno(),
                    presetAttributify(),
                    presetIcons({scale: 1.2, warn: true,}),
                ],
                rules: [
                    ['flex', {display: 'flex'}],
                    [/^p-(\d+)$/, (match: RegExpMatchArray) => ({ padding: `${match[1]}px`})],
                    [/^pl-(\d+)$/, (match: RegExpMatchArray) => ({ paddingLeft: `${match[1]}px`})],
                    [/^pr-(\d+)$/, (match: RegExpMatchArray) => ({ paddingRight: `${match[1]}px`})],
                    [/^m-(\d+)$/, (match: RegExpMatchArray) => ({ margin: `${match[1]}px`})],
                    ['full-w', {width: '100%'}],
                    ['full-h', {height: '100%'}]
                ],
                transformers: [
                    transformerDirectives(),
                    transformerVariantGroup()
                ],
            }),
        ], // 配置sass
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `$injectedColor: orange;`,
                    // 解决控制台告警：The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.
                    api: 'modern-compiler', // or 'modern'
                },
            },
        },
        build: {
            emptyOutDir: true, //若 outDir 在 root 目录下，则 Vite 会在构建时清空该目录
            outDir: `${outDir}`, //指定输出路径
            chunkSizeWarningLimit: 2048,
            assetsDir: 'static', // 指定生成静态资源的存放路径
            rollupOptions: {
                output: {
                    // 入口文件名
                    entryFileNames: `static/js/[name].[hash]_V${version}.js`,
                    // 块文件名
                    chunkFileNames: `static/js/[name].[hash].js`,
                    // 资源文件名 css 图片等等
                    assetFileNames(chunkInfo) {
                        if (chunkInfo.name) {
                            const [name, ext] = path.basename(chunkInfo.name).split('.');
                            return `static/${ext === 'jpg' || ext === 'png' ? 'images' : ext}/${name}.[hash].${ext}`;
                        }
                        return '';
                    },
                    //将模块拆分成多个chunk，减小每个chunk的大小
                    // manualChunks(id) {
                    //     if (id.includes('node_modules')) {
                    //         return id.toString().split('node_modules/')[1].split('/')[0].toString();
                    //     }
                    // },
                },
            }
        },
        server: {
            host: "0.0.0.0",
            port: Number(viteEnv.VITE_APP_PORT),
            open: false,
            proxy: {
                "/api": {
                    target: 'http://127.0.0.1:9528/api',
                    ws: false, // 允许websocket代理
                    changeOrigin: true, // 允许跨域
                    rewrite: (path) => path.replace(/^\/api/, ''),
                },
            },
        },
    };
});
